//
//  LocationManager.swift
//  DaRings
//
//  Created by 魔样科技 on 2022/12/9.
//

import Foundation
import CoreLocation
import UIKit

open class LocationManager: NSObject {
    public static let shared = LocationManager()
    
    public let locationManager = CLLocationManager()
    
    
    private override init() {
        super.init()
        
        self.locationManager.delegate = self
//        self.locationManager.requestWhenInUseAuthorization()
//        self.locationManager.requestAlwaysAuthorization()
//        self.locationManager.startUpdatingLocation()
    }
    
    public func authLocationPermission(opened: @escaping () -> (), closed: @escaping () -> (), cancel: @escaping () -> ()) {
        if self.isOpenLocation() == false {
            closed()
            self.showLocationAlert {
                
            } cancel: {
                cancel()
            }
            return
        }
        opened()
    }
    
    private func isOpenLocation() -> Bool {
        let authStatus = CLLocationManager.authorizationStatus()
        return authStatus != .restricted && authStatus != .denied
    }
    
    public func showLocationAlert(done: @escaping () -> (), cancel: @escaping () -> ()) {
        if let vc = UIViewController.currentViewController() {
            UIAlertController.showPermissionSetting(title: "dialog_gps_training_not_turn_on_location_title".language, message: "", in: vc) { action in
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    if UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.openURL(url)
                    }
                }
                done()
            } cancel: {
                cancel()
            }
        }
    }
    
    
    //MARK: - lazy load

    
}

extension LocationManager: CLLocationManagerDelegate {
    public func locationManager(_ manager: CLLocationManager,
                         didChangeAuthorization status: CLAuthorizationStatus) {
        NotificationCenter.default.post(name: .kReceiveLocationPermissionNotification, object: nil, userInfo: ["result": status])
    }
}
